<?php
namespace App\Services\WxMaterial;

use App\Models\WxMaterial;
use App\Models\WxMaterialExt;
use App\Services\EasyWechat;
use App\Services\SysFileService;
use App\Services\WxErrorService;

/**
 * 图文素材业务逻辑
 * @package App\Services\WxMaterial
 */
class WxMaterialThumb implements WxMaterialInterface
{
    /**
     * 保存素材数据
     * @param $data
     */
    public function save($data)
    {
        if (!isset($data['is_forever'])|| !in_array($data['is_forever'], [0,1])){
            throw new \Exception('请指定素材是否为永久素材');
        }
        if (empty($data['title'])){
            throw new \Exception('请输入缩略图标题');
        }
        if (empty($data['view_url'])){
            throw new \Exception('请提供缩略图地址');
        }
        $findExt = WxMaterialExt::where('view_url', $data['view_url'])->select('material_id','title','description','file_id','view_url')->first();
        if (empty($findExt)){
            \DB::beginTransaction();
            try{
                $materialModel = new WxMaterial;
                $materialModel->cat_id = $data['cat_id'] ?? 0;
                $materialModel->type = 'thumb';
                $materialModel->is_forever = $data['is_forever'];
                $materialModel->save();
                //素材主键ID
                $materialId = $materialModel->material_id;
                if (empty($materialId)){
                    throw new \Exception('生成素材主键无效');
                }
                //素材扩展表
                $extModel = new WxMaterialExt;
                $extModel->material_id = $materialId;
                $extModel->title = $data['title'];
                $extModel->description = $data['description'] ?? '';
                //素材本地文件
                $extModel->view_url = $data['view_url'];
                $localFileInfo = (new SysFileService())->getLocalFileInfoByRemoteUrl($data['view_url']);
                $extModel->file_id = $localFileInfo['file_id'];
                $extModel->save();
                //上传到微信素材
                $app = \App\Services\EasyWechat::officialAccount();
                if ($materialModel->is_forever){//永久
                    $apiRs = $app->material->uploadThumb($localFileInfo['local_file_path']);
                }else{//临时
                    $apiRs = $app->media->uploadThumb($localFileInfo['local_file_path']);
                    $materialModel->expire_time = $apiRs['created_at'] + 86400 * 3;
                }
                //检查微信接口错误
                WxErrorService::checkApiResponse($apiRs);
                $materialModel->media_id = $apiRs['media_id'];
                $materialModel->preview_data = [
                    'title' => $data['title'],
                    'view_url' => $data['view_url'],
                ];
                $materialModel->save();
                \DB::commit();
            }catch (\Exception $e){
                \DB::rollBack();
                throw new \Exception($e->getMessage());
            }
            $materialData = $materialModel->toArray();
            $extData = $extModel->toArray();
            return array_merge($materialData, $extData);
        }else{
            //上传到微信素材
            $app = \App\Services\EasyWechat::officialAccount();
            //素材主数据
            $findMaterial = WxMaterial::where('material_id', $findExt->material_id)->first();
            if (empty($findMaterial)){
                throw new \Exception('素材主数据为空');
            }
            //临时素材更新mediaId
            if ($findMaterial->is_forever == 0 && $findMaterial->expire_time <= time()){
                //素材本地文件
                $localFileInfo = (new SysFileService())->getLocalFileInfoByRemoteUrl($findExt->view_url);
                //重新上传临时素材
                $apiRs = $app->media->uploadThumb($localFileInfo['local_file_path']);
                //检查微信接口错误
                WxErrorService::checkApiResponse($apiRs);
                $findMaterial->media_id = $apiRs['media_id'];
                $findMaterial->expire_time = $apiRs['created_at'] + 86400 * 3;
                $findMaterial->save();
            }
            if ($findMaterial->is_forever == 1 && empty($findMaterial->media_id)){
                //素材本地文件
                $localFileInfo = (new SysFileService())->getLocalFileInfoByRemoteUrl($findExt->view_url);
                $apiRs = $app->material->uploadThumb($localFileInfo['local_file_path']);
                //检查微信接口错误
                WxErrorService::checkApiResponse($apiRs);
                $findMaterial->media_id = $apiRs['media_id'];
                $findMaterial->expire_time = null;
                $findMaterial->save();
            }
            $materialData = $findMaterial->toArray();
            $extData = $findExt->toArray();
            return array_merge($materialData, $extData);
        }
    }

    /**
     * 删除素材
     * @param $materialId
     */
    public function del($materialId)
    {
        // TODO: Implement del() method.
    }

    /**
     * 获取被动回复数据
     * @param $materialId
     */
    public function getPassiveReplyData($materialId)
    {
        // TODO: Implement getReplyData() method.
    }

    /**
     * 获取微信mediaId（临时素材和永久素材处理方式不一样）
     * @param $materialId 素材主键ID
     * @param $reUpload 是否重新上传
     * @return string 素材media_id
     */
    public function getMediaId($materialId, $reUpload = false)
    {
        // TODO: Implement getMediaId() method.
    }

    /**
     * 同步线上数据到本地数据
     */
    public function sync()
    {
        // TODO: Implement sync() method.
    }
}